/**
 *
 * @returns 环境变量中的所需参数
 */
export function getEnvParams() {
  const key =
    process.env.VUE_APP_LOCALSTORAGE_PRE +
    '-' +
    process.env.VUE_APP_ACCESS_TOKEN_KEY
  const token = localStorage.getItem(key)
  const baseUrl = process.env.VUE_APP_HTTP_BASE_URL
  // const functionId = JSON.parse(process.env.VUE_APP_TARGET_FUNCTIONIDS)
  const path = process.env.VUE_APP_DEFAULT_PAGE || ''
  const tokenVal = process.env.VUE_APP_TOKEN || ''
  const clientId = process.env.VUE_APP_CLIENT_ID || ''
  return {
    key,
    baseUrl,
    // functionId,
    token,
    path,
    tokenVal,
    clientId,
  }
}
/**
 *
 * @returns 重定向的url
 */
export function getUrl() {
  const baseUrl = getEnvParams().baseUrl
  let REDIRECT_URI
  if (location.protocol === 'file:') {
    REDIRECT_URI = encodeURIComponent('http://localhost')
  } else {
    REDIRECT_URI = encodeURIComponent(location.href)
  }
  const clientId = getEnvParams().clientId
  const url = `${baseUrl}/oauth/oauth/authorize?response_type=token&client_id=${clientId}&redirect_uri=${REDIRECT_URI}?`
  return url
}

/**
 * 递归对数据进行分类，并对数据根据target进行筛选
 * @param {*} menu 源数据
 * @param {*} targets 需要筛选的id
 * @returns
 */
const getMenuObj = (menu, targets) => {
  const menus = []
  const funcs = []
  menu.subMenus &&
    menu.subMenus.forEach((i) => {
      if (i.subMenus && i.subMenus.length) {
        const menuObj = getMenuObj(i, targets)
        if (menuObj.menus.length || menuObj.funcs.length) {
          menus.push(menuObj)
        }
      } else {
        const isHave =
          (i.functionId && targets.includes(i.functionId.toString())) ||
          !targets ||
          !targets.length
        isHave && funcs.push(i)
      }
    })
  return Object.assign(menu, { menus, funcs })
}

/**
 * 构建分类后的菜单列表，并对数据根据target进行筛选
 * @param {*} list 源数据
 * @param {*} target 需要筛选的id
 * @returns
 */
export function getMenuList(list, targets) {
  if (!list || !list.length) return []
  const result = list
    .map((i) => {
      const obj = getMenuObj(i, targets)
      return obj
    })
    .filter((i) => i.menus.length || i.funcs.length)
  return result
}

/**
 * 递归处理 数据铺平
 * @param {*} menus
 * @returns
 */
export function munusGetFuncs(menus) {
  if (!menus || !menus.length) return []
  let funcs = []
  menus.forEach((i) => {
    if (i.funcs) {
      funcs = funcs.concat(i.funcs)
    }
    if (i.subMenus && i.subMenus.length) {
      funcs = funcs.concat(munusGetFuncs(i.subMenus))
    }
  })
  return funcs
}
